﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Globalization;
using System.Data;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

using Ko2.Portal;

namespace JobCreateInDocs3
{

    public class JobCreateInDocs_Process
    {

        #region Members
        static string sUrl = @"http://localhost/sites/shop";
        static string sListName = "Первичные документы";
        static Ko2.Portal.Env _env = new Ko2.Portal.Env();
        #endregion #region Members

        #region Common Methods
        static public string StringConvertName(String mName)
        {
            return mName.Replace("\"", "'"); ;
        }
        #endregion Common Methods

        #region Job Methods

        public static void Execute(Guid contentDbId)
        {
            Exception err = Execute(contentDbId, sUrl, null);
        }

        public static Exception Execute(Guid contentDbId, string siteStr, SPJobDefinition job)
        {

            #region Members
            Exception ret = null;
            Exception err = null;
            int lcid = CultureInfo.CurrentCulture.LCID;
            string DomainNameStr = _env.GetAppSetting("DomainName");
            int iAllRowsCount = 0;
            int iCurRow = 0;
            string errMsg = "";
            int ErrId = 0;
            int WarningLevel = 1;
            int RetCode = 0;
            bool IsExist = false;
            DateTime dtStart = DateTime.Now;
            DateTime dtEnd = DateTime.Now;
            DateTime dtEndPointShop = DateTime.Now;
            DateTime dtEndPointSuplier = DateTime.Now;
            DateTime dtEndPointReceiptJour = DateTime.Now;
            DateTime dtLastSuccessfullyReceiptJour = new DateTime();
            DateTime dtLastSuccessfullyShops = new DateTime();
            DateTime dtLastSuccessfullySuplier = new DateTime();
            #endregion Members
            #region JobCreateInDocs
            _env.Log_Add("Job", "JobCreateInDocs", "Start", DateTime.Now.ToString()
                , "", 0, 1, 0, 0);
            if (Ko2.Sys.Net.NetInfo.MachineName.ToLower() == "s-wss02"
                || (DateTime.Now.Hour >= 7 && DateTime.Now.Hour <= 23))
            {
                try
                {
                    #region Init (Start)
                    //_____________________________________
                    // Get job lost finale time
                    err = JobCreateInDocsMethods.GetLastsuccessfullyDateTime(ref dtLastSuccessfullyReceiptJour);
                    if (err == null)
                        err = JobCreateInDocsMethods.GetLastsuccessfullyShopsDateTime(ref dtLastSuccessfullyShops);
                    if (err == null)
                        err = JobCreateInDocsMethods.GetLastsuccessfullySuplierDateTime(ref dtLastSuccessfullySuplier);
                    #region If Error
                    if (err != null)
                    {
                        ret = err;
                        errMsg = err.Message;
                        ErrId = 1;
                        RetCode = 1;
                        _env.Log_Add("Job", "JobCreateInDocs", "Error", errMsg
                            , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                        goto TheEndExecute;
                    }
                    #endregion If Error
                    #endregion Init (Start)
                    #region Process
                    if (err == null)
                    {
                        #region Verify Metadata structure Shops
                        err = DBShops.Verify_WSSList_ShopShop(siteStr);
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            _env.Log_Add("Job", "JobCreateInDocs", "Error - Verify Metadata structure - Shops"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #endregion Verify Metadata structure
                        #region Verify Metadata structure Suplier
                        err = DBSuplier.Verify_WSSList_ShopSuplier(siteStr);
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            _env.Log_Add("Job", "JobCreateInDocs", "Error - Verify Metadata structure - Suplier"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #endregion Verify Metadata structure
                        #region Get ReceiptJour DataTable
                        DataTable tbl = new DataTable();
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            err = DBReceiptJour.GetDataByDataTime(ref tbl, dtLastSuccessfullyReceiptJour);
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            _env.Log_Add("Job", "JobCreateInDocs", "Error", errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #region Last DT Convert
                        if (tbl.Rows.Count > 0)
                        {
                            if (tbl.Rows[0]["ModifiedDate"] != DBNull.Value)
                            {
                                dtEndPointReceiptJour =
                                    DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                        tbl.Rows[0]["ModifiedDate"], (int)tbl.Rows[0]["ModifiedTime"]);
                            }
                        }
                        else
                            dtEndPointReceiptJour = dtLastSuccessfullyReceiptJour;
                        #endregion Last DT Convert
                        #endregion Get ReceiptJour DataTable
                        #region Get Shops DataTable
                        DataTable tblShops = new DataTable();
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            err = DBShops.GetDataByDataTime(ref tblShops, dtLastSuccessfullyShops);
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = "DBShops.GetDataByDataTime() : Msg : " + err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            _env.Log_Add("Job", "JobCreateInDocs", "Error"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #region Last DT Convert
                        if (tblShops.Rows.Count > 0)
                        {
                            if (tblShops.Rows[0]["ModifiedDate"] != DBNull.Value)
                            {
                                dtEndPointShop =
                                    DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                        tblShops.Rows[0]["ModifiedDate"], (int)tblShops.Rows[0]["ModifiedTime"]);
                            }
                        }
                        else
                            dtEndPointShop = dtLastSuccessfullyShops;
                        #endregion LastDT Convert
                        #endregion Get Shops DataTable
                        #region Get Suplier DataTable
                        DataTable tblSuplier = new DataTable();
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            err = DBSuplier.GetDataByDataTime(ref tblSuplier, dtLastSuccessfullySuplier);
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = "DBSuplier.GetDataByDataTime() : Msg : " + err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            _env.Log_Add("Job", "JobCreateInDocs", "Error"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #region Last DT Convert
                        if (tblSuplier.Rows.Count > 0)
                        {
                            if (tblSuplier.Rows[0]["ModifiedDate"] != DBNull.Value)
                            {
                                dtEndPointSuplier =
                                    DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                        tblSuplier.Rows[0]["ModifiedDate"], (int)tblSuplier.Rows[0]["ModifiedTime"]);
                            }
                        }
                        else
                            dtEndPointSuplier = dtLastSuccessfullySuplier;
                        #endregion LastDT Convert
                        #endregion Get Suplier DataTable
                        #region Read Data
                        iAllRowsCount += tbl.Rows.Count + tblShops.Rows.Count + tblSuplier.Rows.Count;
                        iCurRow = 0;
                        //___________
                        // Metadata :
                        // Shops :
                        #region Shops
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite site = new SPSite(siteStr))
                            {
                                foreach (DataRow row in tblShops.Rows)
                                {
                                    // Job Progress :
                                    iCurRow++;
                                    if (job != null)
                                        job.UpdateProgress((int)(iCurRow * 100 / iAllRowsCount));
                                    if (row["ID"] == DBNull.Value)
                                        continue;
                                    IsExist = false;
                                    ret = DBShops.IsExist(ref IsExist, sUrl, row["ID"] != DBNull.Value ? row["ID"].ToString() : "" );
                                    if ( ret == null && IsExist==false )
                                    {
                                        #region Insert
                                        err = DBShops.Insert(
                                            sUrl
                                            , StringConvertName(row["NAME"].ToString())
                                            , (row["ID"] != DBNull.Value ? row["ID"].ToString() : "")
                                            , ""
                                            , StringConvertName(row["Addr"].ToString())
                                            );
                                        #endregion Insert
                                        #region If Error
                                        if (err != null)
                                        {
                                            ret = err;
                                            errMsg = err.Message
                                                + " ; ( LoginName -" + site.RootWeb.CurrentUser.LoginName + ")";
                                            ErrId = 2;
                                            RetCode = 2;
                                            _env.Log_Add("Sync", "MetadataSyncShops", "Error", errMsg
                                                , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                                            break;
                                        }
                                        #endregion If Error
                                        // CreateLineLog("Add Shop : " + StringConvertName(reader["NAME"].ToString()));
                                    }
                                    #region Last DT Convert
                                    if (row["ModifiedDate"] != DBNull.Value)
                                    {
                                        DateTime dtTmp = DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                row["ModifiedDate"], (int)row["ModifiedTime"]);
                                        if (dtTmp > dtEndPointShop)
                                            dtEndPointShop =
                                                DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                    row["ModifiedDate"], (int)row["ModifiedTime"]);
                                    }
                                    #endregion LastDT Convert
                                } // foreach
                            } // using (SPSite site = new SPSite(@"http://localhost"))
                        });
                        if (err != null)
                            goto TheEndExecute;
                        #endregion Shops
                        // Company - Suplier
                        #region Suplier
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite site = new SPSite(siteStr))
                            {
                                foreach (DataRow row in tblSuplier.Rows)
                                {
                                    // Job Progress :
                                    iCurRow++;
                                    if (job != null)
                                        job.UpdateProgress((int)(iCurRow * 100 / iAllRowsCount));
                                    if (row["ID"] == DBNull.Value)
                                        continue;
                                    IsExist = false;
                                    ret = DBSuplier.IsExist(ref IsExist, sUrl, row["ID"] != DBNull.Value ? row["ID"].ToString() : "");
                                    if (ret == null && IsExist == false)
                                    {
                                        #region Insert
                                        err = DBSuplier.Insert(
                                            sUrl
                                            , StringConvertName(row["NAME"].ToString())
                                            , (row["ID"] != DBNull.Value ? row["ID"].ToString() : "")
                                            , ""
                                            , StringConvertName(row["FullName"].ToString())
                                            );
                                        #endregion Insert
                                        #region If Error
                                        if (err != null)
                                        {
                                            ret = err;
                                            errMsg = err.Message;
                                            ErrId = 2;
                                            RetCode = 2;
                                            _env.Log_Add("Sync", "MetadataSyncSuplier", "Error", errMsg
                                                , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                                            break;
                                        }
                                        #endregion If Error
                                    }
                                    #region Last DT Convert
                                    if (row["ModifiedDate"] != DBNull.Value)
                                    {
                                        DateTime dtTmp = DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                row["ModifiedDate"], (int)row["ModifiedTime"]);
                                        if (dtTmp > dtEndPointSuplier)
                                            dtEndPointSuplier =
                                                DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                    row["ModifiedDate"], (int)row["ModifiedTime"]);
                                    }
                                    #endregion LastDT Convert
                                } // foreach
                            } // using (SPSite site = new SPSite(@"http://localhost"))
                        });
                        if (err != null)
                            goto TheEndExecute;
                        #endregion Suplier
                        // Documents :
                        #region Documents
                        foreach (DataRow row in tbl.Rows)
                        {
                            err = null;

                            // Job Progress :
                            iCurRow++;
                            if (job != null)
                                job.UpdateProgress((int)(iCurRow * 100 / iAllRowsCount));


                            // Verify InventLocationid
                            IsExist = false;
                            Int64 AxID = -1;
                            try
                            {
                                AxID = Convert.ToInt64(row["RecID"]);
                                err = JobCreateInDocsMethods.inExistsDocs_ByAxId(ref IsExist, AxID);
                            }
                            catch
                            {
                                continue;
                            }
                            
                            if (IsExist==false)
                            {

                                int InventLocationid = -1;
                                try
                                {
                                    InventLocationid = row["InventLocationid"] == DBNull.Value ? -1 : Convert.ToInt32(row["InventLocationid"]);
                                }
                                catch
                                {
                                    continue;
                                }

                                // Insert New Item
                                SPListItem newitem = null;
                                string ShopName = "";
                                string SuplierName = "";
                                int ShopId = -1;
                                int SuplierId = -1;
                                try
                                {                                    
                                    ShopId = Convert.ToInt32(row["InventLocationid"]);                                    
                                    DBShops.IsExist(ref IsExist, ref ShopName, siteStr, ShopId.ToString());                                    
                                    SuplierId = Convert.ToInt32(row["VenderID"]);
                                }
                                catch
                                {
                                    continue;
                                }

                                try
                                {
                                    DBSuplier.IsExist(ref IsExist, ref SuplierName, siteStr, SuplierId.ToString());
                                }
                                catch
                                {
                                    continue;
                                }

                                try
                                {

                                    err = JobCreateInDocsMethods.Add(
                                          ref newitem
                                        , AxID
                                        , ShopId
                                        , SuplierId
                                        , row["PurchId"].ToString()
                                        , JobCreateInDocsMethods.TRIMInvoice(row["PackingSlipId"].ToString())
                                        , DateTime.Parse((string)row["WDate"])
                                        , ShopName
                                        , SuplierName
                                        , row["NETWORKALIAS"].ToString()
                                        );
                                }
                                catch
                                {
                                }

                                 System.Threading.Thread.Sleep(1);
                                
                                if(err != null)
                                {
                                    // Error , not inserted item
                                    #region If Error
                                    //ret = err;
                                    errMsg = "Doc not inserted - " + row["PurchId"].ToString() + "("
                                        + JobCreateInDocsMethods.TRIMInvoice(row["PackingSlipId"].ToString()) + ")"
                                        + DomainNameStr + "\\" + row["NETWORKALIAS"].ToString();
                                    ErrId = 2;
                                    RetCode = 2;
                                    _env.Log_Add("Sync", "JobCreateInDocs", "Documents Sync Error", errMsg
                                        , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                                    // goto TheEndExecute;
                                    continue;
                                    #endregion If Error
                                }

                            } // if exist
                            #region Last DT Convert
                            if (row["ModifiedDate"] != DBNull.Value)
                            {
                                DateTime dtTmp = DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                    row["ModifiedDate"], (int)row["ModifiedTime"]);
                                if (dtTmp > dtEndPointReceiptJour)
                                    dtEndPointReceiptJour =
                                        DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                            row["ModifiedDate"], (int)row["ModifiedTime"]);
                            }
                            #endregion LastDT Convert
                        } // foreach
                        #endregion Documents
                        #endregion Read Data
                    }
                    #endregion Process
                    #region If Error
                    if (err != null)
                    {
                        ret = err;
                        errMsg = err.Message;
                        ErrId = 2;
                        RetCode = 2;
                        _env.Log_Add("Job", "JobCreateInDocs", "Error", errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                        goto TheEndExecute;
                    }
                    #endregion End If Error
                    #region Save Final date time
                    dtEnd = DateTime.Now;
                    if (err == null)
                    {
                        err = JobCreateInDocsMethods.SetLastsuccessfullyDateTime(dtEndPointReceiptJour);
                        if (err == null)
                            err = JobCreateInDocsMethods.SetLastsuccessfullyShopsDateTime(dtEndPointShop);
                        if (err == null)
                            err = JobCreateInDocsMethods.SetLastsuccessfullySuplierDateTime(dtEndPointSuplier);
                    }
                    #endregion Save Final date time
                }
                #region Catch
                catch (Exception ex)
                {
                    ret = new Exception(ex.Message, ex);
                    errMsg = ex.Message;
                    ErrId = 1;
                    RetCode = 1;
                    _env.Log_Add("Job", "JobCreateInDocs", "Error", errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                }
                #endregion Catch
            } // if()
            #region End JobCreateInDocs
        TheEndExecute:
            _env.Log_Add("Job", "JobCreateInDocs", "Stop", DateTime.Now.ToString()
                , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
            #endregion End
            #endregion JobCreateInDocs
            #region Clear Logs
            DateTime dtFrom = DateTime.Now;
            TimeSpan span = new TimeSpan(90, 0, 0, 0);
            dtFrom = dtFrom - span;
            err = DBSPLog.Delete(dtFrom);
            #endregion Clear Logs

            return ret;
        }

        #endregion

    }

}
